package cn.wolfcode.p2p.business.service.impl;
import java.math.BigDecimal;

import cn.wolfcode.p2p.base.domain.Account;
import cn.wolfcode.p2p.base.service.IAccountService;
import cn.wolfcode.p2p.business.domain.PlatformBankInfo;

import cn.wolfcode.p2p.base.domain.BaseAuditDomain;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.business.domain.RechargeOffline;
import cn.wolfcode.p2p.business.mapper.RechargeOfflineMapper;
import cn.wolfcode.p2p.business.query.RechargeOfflineQuery;
import cn.wolfcode.p2p.business.service.IAccountFlowService;
import cn.wolfcode.p2p.business.service.IRechargeOfflineService;
import cn.wolfcode.p2p.util.AssertUtil;
import cn.wolfcode.p2p.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RechargeOfflineServiceImpl implements IRechargeOfflineService {
    @Autowired
    private RechargeOfflineMapper rechargeOfflineMapper;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountFlowService accountFlowService;

    @Override
    public void save(RechargeOffline ro) {
        //判断参数
        LoginInfo currentUser = UserContext.getCurrentUser();
        ro.setApplier(currentUser);
        ro.setApplyTime(new Date());
        rechargeOfflineMapper.insert(ro);
    }

    @Override
    public PageInfo query(RechargeOfflineQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<RechargeOffline> list = rechargeOfflineMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void audit(Long id, Integer state, String remark) {
        //判断参数
        //是否处于待审核状态
        RechargeOffline ro = rechargeOfflineMapper.selectByPrimaryKey(id);
        AssertUtil.instance().isFalse(ro.getState() != BaseAuditDomain.STATE_NORMAL, "您当前不处于待审核状态");
        //设置当前充值对象
        ro.setState(state);
        ro.setRemark(remark);
        ro.setAuditor(UserContext.getCurrentUser());
        ro.setAuditTime(new Date());
        if (state == BaseAuditDomain.STATE_SUCCESS) {
            //审核成功
            //修改账户余额
            LoginInfo applier = ro.getApplier();
            Account account = accountService.getById(applier.getId());
            account.addUsableAmount(ro.getAmount());
            accountService.update(account);
            //保存充值流失记录
            accountFlowService.createRechargeFlow(ro, account);

        }else{
           // 审核失败
            //都做了,没什么做的
        }
        //设置充值对象的审核信息
        update(ro);

    }

    public void update(RechargeOffline ro){
        AssertUtil.instance().isFalse(rechargeOfflineMapper.updateByPrimaryKey(ro) == 0, "线下充值修改失败,乐观锁异常["+  ro.getId() + "]");
    }
}
